package com.imay.live.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.helper.NetworkHelper;
import com.imay.base.util.MD5Util;
import com.imay.live.fragment.user.UserBaseFragment;
import com.imay.live.helper.CallBack;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.H5Helper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.manager.EditTextManager;
import com.imay.live.model.OnlineModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.base.util.SpannableStringUtils;
import com.imay.live.utils.ToastUtil;
import com.imay.live.R;


/**
 * Created by chan on 2017/3/28.
 */

public class LoginActivity extends UserBaseActivity implements View.OnClickListener {

    private final int REQUEST_CODE = 200;
    private TextView mLocalView, mLoginSure;
    private String local = "86";
    private EditText mEtPhone, mEtPsd;

    private boolean isSecret = false;

    private EditTextManager manager;

    public static void startActivity(Activity activity, String fromurl) {
        Intent intent = new Intent(activity, LoginActivity.class);
        if (!TextUtils.isEmpty(fromurl)) {
            intent.putExtra(H5Helper.H5REDIRECTION_KEY, fromurl);
        }
        activity.startActivity(intent);
    }

    public static void startActivityForResult(Activity activity, final int requestCode) {
        Intent intent = new Intent(activity, LoginActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startActivityForLogout(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        manager = EditTextManager.getInstance();

        setTitle(getString(R.string.str_login_title));
        TextView textView = new TextView(this);
        textView.setTextSize(14);
        textView.setTextColor(getResources().getColor(R.color.text_20));
        textView.setText(getString(R.string.str_register_text));
        textView.setPadding(0, 0, (int) getResources().getDimension(R.dimen.dp_10), 0);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toResigter();
            }
        });
        getTitleBar().getRightView().addView(textView);
        getTitleBar().setBackgroundColor(Color.WHITE);


        mEtPhone = $(R.id.et_login_phone);
        mEtPsd = $(R.id.et_login_psd);
        mLoginSure = $(R.id.tv_login_sure);

        ((TextView) $(R.id.tv_respsd)).setText(SpannableStringUtils.getBuilder(getString(R.string.str_reset_psd)).setUnderline().create());
        $(R.id.tv_respsd).setOnClickListener(this);
        mLoginSure.setOnClickListener(this);

        mEtPsd.setTag("psd");
        manager.changeBgColor(mLoginSure, R.drawable.shape_corner100_bc, R.drawable.shape_corner100_9e, mEtPhone, mEtPsd);
        String phone = PreferenceHelper.getInstance().getPhone();

        if (!TextUtils.isEmpty(phone)) {
            mEtPhone.setText(phone);
        }

        String psd = PreferenceHelper.getInstance().getSec();
        isSecret = false;
        if (!TextUtils.isEmpty(psd)) {
            psd = psd.substring(0, 10);
            isSecret = true;
            mEtPsd.setText(psd);
        }

        mLocalView = $(R.id.tv_area_local);
        int local = PreferenceHelper.getInstance().getPhoneCountry();
        if (local != -1) {
            mLocalView.setText("+" + local);
        }
        mLocalView.setOnClickListener(this);

        manager.setEditClear((ImageView) $(R.id.iv_phone_clear), mEtPhone, mEtPsd);
        manager.setEditClear((ImageView) $(R.id.iv_psd_clear), mEtPsd);
    }

    /**
     * 跳转至注册界面
     */
    protected void toResigter() {
        ResigterActivity.startActivityForResult(this, ResigterActivity.STATUS_REGISTER, UserBaseFragment.REQUEST_RESIGTER);
    }

    @Override
    protected boolean isTranslucentStatus() {
        return false;
    }

    // 登录
    private void login() {
        if (TextUtils.isEmpty(local)) {
            return;
        }
        final int localNum = Integer.parseInt(local);

        final CharSequence phoneStr = mEtPhone.getText();
        long phone = 0;
        if (TextUtils.isEmpty(phoneStr)) {
            return;
        }

        final CharSequence psdStr = mEtPsd.getText();
        if (TextUtils.isEmpty(psdStr)) {
            return;
        }

        phone = Long.parseLong(phoneStr.toString());

        final String secret;
        if (isSecret) {
            String sec = PreferenceHelper.getInstance().getSec();
            if (sec != null) {
                final String secSub = sec.substring(0, 10);
                if (secSub.endsWith(psdStr.toString())) {
                    secret = sec;
                } else {
                    secret = MD5Util.getMD5(phoneStr.toString() + psdStr.toString());
                }
            } else {
                secret = MD5Util.getMD5(phoneStr.toString() + psdStr.toString());
            }
        } else {
            secret = MD5Util.getMD5(phoneStr.toString() + psdStr.toString());
        }

        final String finalPhone = Long.toString(phone);
        AccountManager.getInstance().loginByPasswordHttp(localNum, phone, secret, new CallBack() {
            @Override
            public void onSuccess() {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());

                PreferenceHelper.getInstance().saveUserInf(localNum, finalPhone, secret);

                ToastUtil.showImg(LoginActivity.this, getString(R.string.str_login_success), R.mipmap.jiaohutishidagou_3x, 200);
                // 登录时，传递分享回调参数
                    /*if (first) {
                        SuggestActivity.startActivity(LoginActivity.this);
                    } else {*/
                //MainActivity2.startActivity(LoginActivity.this, getIntent().getStringExtra(H5Helper.H5REDIRECTION_KEY));
                //}
                //ActivityHelper.getInstance().finishActivity(UserActivity.class);
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(int code, String message) {
                DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                if (AccountManager.getInstance().isLogined()) {
                    setResult(RESULT_OK);
                    finish();
                } else {
                    ToastUtil.showImg(LoginActivity.this, ErrorResult.getString(LoginActivity.this, code), R.mipmap.jiaohutishidaxia_3x, 200);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onClick(final View view) {
        switch (view.getId()) {
            case R.id.tv_respsd:
                ResigterActivity.startActivityForResult(this, ResigterActivity.STATUS_FORGOT_PASSWORD_AUTO_LOGIN, UserBaseFragment.REQUEST_RESIGTER);
                break;
            case R.id.tv_login_sure:

                if (!NetworkHelper.getInstance().hasConnection()) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ErrorResult.toastError(this, ResultCode.CodeNetErrorAction);
                    return;
                }

                view.setClickable(false);


                final CharSequence phoneStr = mEtPhone.getText();
                long phone = 0;
                if (TextUtils.isEmpty(phoneStr)) {
                    return;
                }

                phone = Long.parseLong(phoneStr.toString());

                if (AccountManager.getInstance().isLogined()) {
                    setResult(RESULT_OK);
                    finish();
                    return;
                }
                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_login_loading));
                view.setClickable(true);
                ProtoRequestHelper.task(ProtoHttpFactory.checkOnline(local, phoneStr.toString())).setTag(this.hashCode()).request(new ProtoCallBack() {
                    @Override
                    public void onRequestSuccess(String command, String data) {
                        view.setClickable(true);
                        Result<OnlineModel> result = JSON.parseObject(data, new TypeReference<Result<OnlineModel>>() {
                        }.getType());
                        if (result.result == ResultCode.CodeSuccess) {
                            if (!result.data.isOnline()) { //没有在线
                                login();
                            } else { //在线情况下，提示框
                                if (result.data.isYourSelf()) {
                                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                                    setResult(RESULT_OK);
                                    finish();
                                } else {
                                    DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.str_login_relogin), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            login();
                                        }
                                    }, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                                        }
                                    });
                                }
                            }
                        } else {
                            DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                            ToastUtil.showImg(LoginActivity.this, ErrorResult.getString(LoginActivity.this, result.result), R.mipmap.jiaohutishidaxia_3x, 200);
                        }
                    }

                    @Override
                    public void onRequestError(String command, int code, String message) {
                        view.setClickable(true);
                        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                        ToastUtil.showImg(LoginActivity.this, ErrorResult.getString(LoginActivity.this, code), R.mipmap.jiaohutishidaxia_3x, 200);
                    }
                });
                break;
            case R.id.tv_area_local:
                LocalActivity.startActivity(this, REQUEST_CODE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                local = data.getStringExtra("local_text");
                mLocalView.setText("+" + local);
            }
        } else if (requestCode == UserBaseFragment.REQUEST_RESIGTER) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }
}
